package cqrtplm.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hustcad.plm.basic.util.TyplmEntityBaseUtil;
import com.hustcad.plm.pdm.ec.module.dto.TyplmChangeIssueDetailDTO;
import com.hustcad.plm.pdm.ec.service.TyplmChangeIssueService;
import com.ty.basic.entity.org.UserDO;
import com.ty.basic.service.snow.SnowflakeIdComponent;
import com.ty.basic.session.TyAccountContext;
import cqrtplm.constant.RTErrorCodeEnum;
import cqrtplm.entity.ProblemJurisdictionDO;
import cqrtplm.mapper.ProblemJurisdictionMapper;
import cqrtplm.service.RTProblemJurisdictionService;
import cqrtplm.vo.IssueTypeVO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import reactor.core.publisher.Flux;

import javax.annotation.Resource;
import java.math.BigInteger;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author：lotus
 * @DATE: 2025/7/29 20:27
 */
@Transactional
@Service
public class RTProblemJurisdictionServiceImpl implements RTProblemJurisdictionService {

    @Resource
    private ProblemJurisdictionMapper problemJurisdictionMapper;
    @Resource
    private SnowflakeIdComponent snowflakeIdComponent;
    @Resource
    private TyplmChangeIssueService typlmChangeIssueService;

    @Value("${issue.type.oid}")
    private String issueTypeOid;

    @Override
    public PageInfo<ProblemJurisdictionDO> queryProblemJurisdictionAll(Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<ProblemJurisdictionDO> problemJurisdictionDOS = problemJurisdictionMapper.queryProblemJurisdictionAll();
        return new PageInfo<>(problemJurisdictionDOS);
    }

    @Override
    public void deleteProblemJurisdictionByOid(String oid) {
        problemJurisdictionMapper.deleteProblemJurisdictionByOid(oid);
    }

    @Override
    public void insertProblemJurisdiction(ProblemJurisdictionDO problemJurisdictionDO) {

        List<ProblemJurisdictionDO> problemJurisdictionDOS = problemJurisdictionMapper.queryProblemJurisdictionByUid(
                problemJurisdictionDO.getUserOid());
        if (CollUtil.isNotEmpty(problemJurisdictionDOS)){
            return;
        }
        TyplmEntityBaseUtil.fillCommonFieldForCreate(problemJurisdictionDO);
        problemJurisdictionDO.setOid(snowflakeIdComponent.getInstance().nextId());
        problemJurisdictionMapper.insertProblemJurisdiction(problemJurisdictionDO);
    }

    @Override
    public void updateProblemJurisdiction(ProblemJurisdictionDO problemJurisdictionDO) {
        TyplmEntityBaseUtil.fillCommonFieldForCreate(problemJurisdictionDO);
        problemJurisdictionMapper.updateProblemJurisdiction(problemJurisdictionDO);

    }

    @Override
    public Map<String, List<String>> queryIssueTypeAndAttr() {

        return problemJurisdictionMapper.selectIssueType(issueTypeOid)
                .stream()
                // 过滤无效的IssueTypeVO（自身为null或TypeOid为null）
                .filter(Objects::nonNull)
                .filter(vo -> vo.getTypeOid() != null)
                // 构建TypeOid->TypeName的映射（处理重复TypeOid）
                .collect(Collectors.toMap(
                        IssueTypeVO::getTypeOid,
                        vo -> Optional.ofNullable(vo.getTypeName()).orElse("未知类型"),
                        (existing, replacement) -> existing
                ))
                // 遍历映射，构建最终结果
                .entrySet()
                .stream()
                .collect(Collectors.toMap(
                        Map.Entry::getValue,
                        entry -> {
                            // 查询问题OID列表
                            List<BigInteger> changeIssueOidList = Optional.ofNullable(
                                    problemJurisdictionMapper.selectChangeIssue(entry.getKey())
                            ).orElse(Collections.emptyList());

                            if (CollUtil.isEmpty(changeIssueOidList)) {
                                return Collections.emptyList();
                            }
                            // 解析每个问题的Importance值
                            return changeIssueOidList.stream()
                                    .filter(Objects::nonNull)
                                    .map(oid -> Optional.ofNullable(
                                                 this.typlmChangeIssueService.queryChangeIssueDetail(oid)
                                         ).orElse(new TyplmChangeIssueDetailDTO())
                                    )
                                    .map(detail -> {
                                        String formDataStr = Optional.ofNullable(detail.getFormData()).orElse("{}");
                                        JSONObject formData = JSONObject.parseObject(formDataStr);
                                        return Optional.ofNullable(formData)
                                                .map(json -> json.getString("Importance"))
                                                .orElse(null);
                                    })
                                    .filter(StringUtils::isNotBlank)
                                    .distinct()
                                    .collect(Collectors.toList());
                        }
                ));

    }

}
